// components/customer-tag/customerTag.js
const app = getApp()
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    customerId: {
      type: String,
      value: '',
      observer (customerId) {
        this.getCustomerTags()
      }
    },
    origin: String,
    btnName: String
  },

  /**
   * 组件的初始数据
   */
  data: {
    tags: [],
    CDNPATH: app.globalData.CDNPATH,
    curIndex: 1,
    age: 0,
    sex: '',
    maskshow: false,
    desc: '',
    countdownTime: 0,
    portraitPos: {},
    touch: false,
    tagList: [],
    movingTag: {},
    movingPos: {
      x: 0,
      y: 0
    },
    typePos: {
      height: 0,
      index: 1
    },
    scrollEndTimer: -1,
  },
  options: {
    addGlobalClass: true
  },
  created: function () {
    this.getTagList()
  },
  ready () {
    let query = this.createSelectorQuery()
    query.select('#portrait').boundingClientRect((rect) => {
      const portraitPos = {
        left: rect.left,
        top: rect.top,
        right: rect.right,
        bottom: rect.bottom,
      }
      this.setData({portraitPos})
    }).exec()
    query.select('.type-list').boundingClientRect((rect) => {
      console.log(rect.height / 3)
      this.setData({
        'typePos.height': rect.height / 3
      })
    }).exec()
  },
  /**
   * 组件的方法列表
   */
  methods: {
    getTagList: function (params) {
      app.api.post({
        url: 'tag_manage_all',
      }).then(res => {
        this.setData({
          tags: res
        })
      })
    },
    onLongPress: function (e) {
      const { item } = e.currentTarget.dataset
      const { tagList } = this.data
      const hasTag = tagList.some(tag => item.type === tag.type)
      if (!hasTag) {
        this.setData({
          touch: true,
          movingTag: item,
          'movingPos.x': -1000,
          'movingPos.y': -1000,
        })
        let query = this.createSelectorQuery()
        query.select('.moving-tag').boundingClientRect((rect) => {
          console.log(rect.width)
          const { width, height } = rect
          this.setData({
            'movingPos.width': width,
            'movingPos.height': height,
          })
        }).exec()
      }
    },
    onTouchMove: function (e) {
      if (this.data.touch) {
        const {pageX, pageY} = e.changedTouches[0]
        this.setData({
          'movingPos.x': pageX,
          'movingPos.y': pageY,
        })
      }
    },
    onTouchEnd: function (e) {
      const { portraitPos, touch } = this.data
      if (touch) {
        const {pageX, pageY} = e.changedTouches[0]
        const { item } = e.currentTarget.dataset
        const {left, top, right, bottom} = portraitPos
        if (pageX >= left && pageX <= right && pageY >= top && pageY <= bottom) {
          let { tagList } = this.data
          tagList.push({...item, tagName: item.name, tagId: item.id})
          this.setData({tagList})
        }
      }
      this.setData({ touch: false })
    },
    next: function () {
      const tagList = this.data.tagList.map(({tagId, type}) => ({tagId, type}))
      if (this.data.origin === '1') {
        app.api.post({
          url: 'customer_tag_add',
          data: {
            customerId: this.data.customerId,
            tagList
          }
        }).then((res) => {
          console.log(res)
          app.api.post({
            url: 'customer_tag_customerComment',
            data: {
              id: this.data.customerId
            }
          }).then(res => {
            if (res.remark === '') {
              wx.navigateTo({
                url: `/pages/home-page/customer-analysis/customerAnalysis?id=${this.data.customerId}`
              })
            } else {
              this.setData({
                desc: res.remark,
                maskshow: true
              })
              this.countdown()
            }
          })
        })
      } else {
        app.api.post({
          url: 'customer_tag_add',
          data: {
            customerId: this.data.customerId,
            tagList
          }
        }).then(res => {
          this.triggerEvent('saveTag', { info: this.data.info }, {});
        })
      }
    },
    closeMask: function () {
      this.setData({
        maskshow: false
      })
    },
    countdown: function () {
      let countdownTime = 3
      this.setData({
        countdownTime
      })
      var countdown = setInterval(() => {
        if( countdownTime == 0 ){
          this.setData({
            countdownTime: 0,
            maskshow: false,
          });
          // 取消定时器
          clearInterval(countdown);
          wx.navigateTo({
            url: `/pages/home-page/customer-analysis/customerAnalysis?id=${this.data.customerId}`
          })
        } else {
          this.setData({
            countdownTime: --countdownTime,
          });
        }
      }, 1000);
    },
    tapPrev: function () {
      const { height, index } = this.data.typePos
      this.setData({
        'typePos.index': (index - 1),
        'typePos.scrollTop': (index - 1) * height,
      })
    },
    tapNext: function () {
      const { height, index } = this.data.typePos
      if (index < this.data.tags.length - 1) {
        this.setData({
          'typePos.index': index + 1,
          'typePos.scrollTop': (index + 1) * height,
        })
      }
    },
    getCustomerTags: function (params) {
      app.api.post({
        url: 'customer_tag_list',
        data: {
          customerId: this.data.customerId
        }
      }).then(res => {
        console.log(res)
        this.setData({
          tagList: res.tagList,
          age: res.age,
          sex: res.sex
        })
      })
    },
    delTag: function (e) {
      const { index } = e.currentTarget.dataset
      let { tagList } = this.data
      tagList.splice(index, 1)
      this.setData({tagList})
    },
    moveType (e) {
      const { height } = this.data.typePos
      const index = Math.ceil(e.detail.scrollTop / height - 1) + 1
      this.setData({
        'typePos.index': index,
      })
      if (this.scrollEndTimer) {
        clearTimeout(this.scrollEndTimer)
        this.scrollEndTimer = null
      }

      this.scrollEndTimer = setTimeout(() => {
        console.log('滑动结束')
        this.setData({
          'typePos.scrollTop': index * height,
        })
      }, 100)
    }
  }
})
